package org.begincode.admin.control;

import org.begincode.admin.service.ResourceService;
import org.begincode.admin.service.ResourceTypeService;
import org.begincode.core.model.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangsj on 2016/5/2.
 * 资源管理
 */
@Controller
@RequestMapping("resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private ResourceTypeService resourceTypeService;

    @RequestMapping(value = {"/init"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String initResource(Model model) {
        model.addAttribute("resourceTypes", this.resourceTypeService.findResourceType());
        return "/admin/resourceEdit";
    }

    @RequestMapping(value = {""}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public Map addResource(Resource resource) {
        Map message = new HashMap();
        message.put("msg", "保存成功");
        resource.setCreateDatetime(new Date());
        resource.setDelFlag("1");
        resource.setResourceAbstract(HtmlUtils.htmlEscape(resource.getResourceAbstract()));
        resource.setResourceName(HtmlUtils.htmlEscape(resource.getResourceName()));
        resource.setDownCount(Integer.valueOf(0));
        if ((resource.getResourceId() != null) && (resource.getResourceId().intValue() != 0)) {
            int returnValue = this.resourceService.updateByPrimaryKeyWithBLOBs(resource);
            if (returnValue <= 0)
                message.put("msg", "保存失败");
        } else {
            this.resourceService.createResource(resource);
            if ((resource.getResourceId() == null) || (resource.getResourceId().intValue() == 0)) {
                message.put("msg", "保存失败");
            }
        }
        return message;
    }
}
